<template>
  <view class="diyPhoneCase-page">
    <hs-status-bar></hs-status-bar>
    <top-bar :title="'DIY定制'" :haveBack="true"></top-bar>

    <canvas
      canvas-id="drawCanvas"
      style="
        width: 750rpx;
        height: 750rpx;
        position: absolute;
        left: -750rpx;
        top: -750rpx;
        background: #fff;
        z-index: 99;
      "
    ></canvas>
    <hs-phoneModel
      :materialList="materialList"
      material-type="diyPhoneCase"
      ref="phoneModel"
      @handleSelectModel="selectPhoneModel"
      @handleSelectMaterial="selectMaterial"
    ></hs-phoneModel>

    <view class="decorate-content">
      <!-- <view class="tips" v-if="!canEdit">
				请先挑选机壳
			</view> -->
      <!-- 编辑区 -->
      <view class="eidt-view" @click="editViewClick">
        <diy-edit
          :topMaterialUrl="topMaterialUrl"
          :bottomMaterialUrl="bottomMaterialUrl"
          :list="activeDecorates"
          ref="diyEdit"
          @copyDecorate="copyDecorate"
          @removeDecorate="removeDecorate"
          @writeHistory="writeHistory"
          @changeDecorate="changeDecorate"
        ></diy-edit>
      </view>
      <!-- 素材切换栏 -->
      <view class="type-tabbar">
        <!-- 贴纸 -->
        <view
          class="type-item"
          :class="{ active: decorateType == 0 }"
          @click="selectDecorateType(0)"
        >
          <image src="@/static/images/icon/tiezhi.png" mode="aspectFit"></image>
          <view class="text"> 贴纸 </view>
        </view>
        <!-- 配饰 -->
        <!-- <view class="type-item" :class="{active:decorateType==1}" @click="selectDecorateType(1)">
					<image src="@/static/images/icon/xiaoxiong.png" mode="aspectFit"></image>
					<view class="text">
						配饰
					</view>
				</view> -->
        <!-- AI人像 -->
        <view
          class="type-item"
          :class="{ active: decorateType == 2 }"
          @click="selectDecorateType(2)"
        >
          <image
            src="@/static/images/icon/aituxiang.png"
            mode="aspectFit"
          ></image>
          <view class="text"> AI图像 </view>
        </view>
        <!-- 模板 -->
        <view
          class="type-item"
          :class="{ active: decorateType == 3 }"
          @click="selectDecorateType(3)"
        >
          <image src="@/static/images/icon/moban.png" mode="aspectFit"></image>
          <view class="text"> 模板 </view>
        </view>
        <!-- 照片 -->
        <view
          class="type-item"
          :class="{ active: decorateType == 4 }"
          @click="selectDecorateType(4)"
        >
          <image
            src="@/static/images/icon/zhaopian.png"
            mode="aspectFit"
          ></image>
          <view class="text"> 照片 </view>
        </view>
      </view>
      <!-- 操作栏 -->
      <view class="operation-tabbar">
        <view class="left-control">
          <!-- 前进后退 -->
          <image
            src="@/static/images/icon/next.png"
            mode="aspectFit"
            class="control-btn"
            :class="{ disable: historyIndex == 0 }"
            @click="backward"
          >
          </image>
          <image
            src="@/static/images/icon/next.png"
            mode="aspectFit"
            class="control-btn next"
            :class="{ disable: historyIndex == history.length - 1 }"
            @click="forward"
          ></image>
          <!-- 位置微调 -->
          <view v-if="isFocus" class="translate">
            <image
              src="@/static/images/icon/jiantou.png"
              mode="aspectFit"
              class="control-btn left"
              @touchstart="translateDecorate(-2, 0)"
              @touchend="translateDecorateEnd()"
            ></image>
            <image
              src="@/static/images/icon/jiantou.png"
              mode="aspectFit"
              class="control-btn up"
              @touchstart="translateDecorate(0, -2)"
              @touchend="translateDecorateEnd()"
            ></image>
            <image
              src="@/static/images/icon/jiantou.png"
              mode="aspectFit"
              class="control-btn down"
              @touchstart="translateDecorate(0, 2)"
              @touchend="translateDecorateEnd()"
            ></image>
            <image
              src="@/static/images/icon/jiantou.png"
              mode="aspectFit"
              class="control-btn right"
              @touchstart="translateDecorate(2, 0)"
              @touchend="translateDecorateEnd()"
            ></image>
          </view>
        </view>
        <!-- 层级调整 -->
        <view class="coverage" @click="showCoverage">
          <image src="@/static/images/icon/cengji.png" mode="aspectFit"></image>
        </view>
      </view>
      <!-- 素材列表 -->
      <view
        class="<strong>decorate-list</strong>"
        :class="{ more: moreDecorate, hide: decorateType == null }"
      >
        <view class="more" @click="moreDecorate = !moreDecorate">
          {{ moreDecorate ? "收起 -" : "展开 +" }}
        </view>
        <!-- <text v-if="decorateType==1" class="tips1">注：配饰会以实物的形式贴在手机壳上，无法调整大小</text> -->
        <u-tabs
          v-if="decorateType == 0 || decorateType == 2 || decorateType == 3"
          lineWidth="0"
          lineHeight="30"
          :itemStyle="{ width: '20%', height: '50rpx' }"
          :inactiveStyle="{ color: '#807D7E', fontSize: '26rpx' }"
          :activeStyle="{
            color: '#3C4242',
            fontSize: '26rpx',
            fontWeight: '700',
          }"
          :list="
            decorateType == 0
              ? decorationTagList
              : decorateType == 2
              ? stickerTagList
              : templateTagList
          "
          @change="switchDecorateTab"
          :current="decorateTabsIndex"
        >
        </u-tabs>
        <scroll-view scroll-y="true" class="decorate-scroll">
          <!-- 贴纸 -->
          <view class="list" v-if="decorateType == 0">
            <view
              class="decorate-item"
              v-for="item of decorationList"
              :key="item.id"
              v-show="
                item.tagIds.includes(decorateTabsId) || decorateTabsId == 0
              "
              @click="selectDecorate(item, 0)"
              :class="{ active: activeDecorates.includes(item) }"
            >
              <radio
                checked
                class="radio"
                v-if="activeDecorates.includes(item)"
              />
              <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
            </view>
          </view>
          <!-- 配饰 -->
          <!-- 					<view class="list" v-if="decorateType==1">
						<view class="decorate-item" v-for="item of accessoriesList" :key="item.id"
							@click="selectDecorate(item,1)" :class="{active:activeDecorates.includes(item)}">
							<radio checked class="radio" v-if="activeDecorates.includes(item)" />
							<image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
						</view>
					</view> -->
          <!-- AI人像 -->
          <view class="list ai-list" v-if="decorateType == 2">
            <view
              class="decorate-item"
              :class="{ active: activeDecorates.includes(item) }"
              :style="item.type == 21 ? 'height: 165rpx;' : ''"
              v-for="item of stickerImageList"
              :key="item.id"
              v-show="item.type == decorateTabsId"
              @click="selectDecorate(item, 2)"
            >
              <radio
                checked
                class="radio"
                v-if="activeDecorates.includes(item)"
              />
              <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
            </view>

            <!--  -->
          </view>
          <!-- <u-button style="width: 200rpx;" v-if="noneAiImage" type="primary" :plain="true" text="去生成ai图像"></u-button> -->
          <view
            class="get-ai-image"
            v-if="noneAiImage && decorateType == 2"
            @click="getAiImage"
          >
            <view class="get-ai-image-text"> 去生成AI图像 </view>
          </view>
          <!-- 模板 -->
          <view class="list" v-if="decorateType == 3">
            <view
              class="decorate-item temp-item"
              v-for="item of templateList"
              :key="item.id"
              v-show="item.subType == decorateTabsId"
              @click="getTemplateInfo(item.id, item.subType)"
              :class="{ active: activeDecorates.includes(item) }"
            >
              <radio
                checked
                class="radio"
                v-if="activeDecorates.includes(item)"
              />
              <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
            </view>
          </view>
          <!-- 照片 -->
          <view class="list" v-if="decorateType == 4">
            <view class="decorate-item upload" @click="uploadImage">
              <image src="../../static/images/icon/add.png" mode=""></image>
              <view class="text"> 上传照片 </view>
            </view>
            <view
              class="decorate-item"
              v-for="item of customStickerImageList"
              :key="item.id"
              @click="selectDecorate(item, 30)"
              :class="{ active: activeDecorates.includes(item) }"
            >
              <radio
                checked
                class="radio"
                v-if="activeDecorates.includes(item)"
              />
              <image :src="item.imageUrl" lazy-load mode="aspectFit"></image>
              <view class="delete" @click.stop="deleteImage(item.id)"> × </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <view class="btn">
      <view class="btn-next" @click="save" :class="{ disable: !canEdit }">
        确定
      </view>
    </view>
    <view class="">
      <coverage
        ref="coverage"
        @changeIndex="changeIndex"
        @remove="removeDecorate"
        :controlsList="activeDecorates"
        :containerSize="{
          width: '300rpx',
          height: 'calc(100vh - 220rpx)',
          overflow: 'scroll',
        }"
        :controlsSize="{ width: 170, height: 60 }"
      ></coverage>
    </view>
  </view>
</template>

<script>
import {
  getSkuList,
  getCustomDetail,
  getDecorateList,
  deleteImage,
} from "@/api/custom.js";
import {
  drawCanvas,
  generateCanvas,
  submitCustomImage,
  uploadStickerImage,
} from "@/utils/utils.js";
import { mapGetters } from "vuex";
import diyEdit from "@/pages/diy/components/diy-edit.vue";
import {
  connect_throttle,
  connect_debounce
} from "@/utils/throttle.js"; //节流
export default {
  components: {
    diyEdit,
  },
  data() {
    return {
      img: "",
      infoData: {},
      tabsList: [
        {
          name: "图案",
          index: 0,
        },
        {
          name: "机壳",
          index: 1,
        },
        {
          name: "制作",
          index: 2,
        },
      ],
      /* material */
      materialList: [],
      activeMaterialId: null,
      activeMaterialMap: {},
      topMaterialUrl: "",
      bottomMaterialUrl: "",
      pageSize: 20,
      /* decorate */
      decorationTagList: [],
      templateTagList: [
        {
          index: 0,
          id: 1,
          name: "整图背景",
          type: 1,
        },
        {
          index: 1,
          id: 3,
          name: "透明背景",
          type: 3,
        },
        {
          index: 2,
          id: 2,
          name: "模板",
          type: 2,
        },
      ], //模板tag标签
      stickerTagList: [
        {
          index: 2,
          id: 23,
          name: "AI字体",
          type: 23,
        },
        {
          index: 0,
          id: 21,
          name: "AI人像",
          type: 21,
        },
        {
          index: 1,
          id: 22,
          name: "AI背景",
          type: 22,
        },
      ], // ai图像标签
      decorateTabsId: 0, //选中的贴纸标签
      decorateTabsIndex: 0,
      moreDecorate: false,
      activeDecorates: [],
      decorationList: [], // 贴纸列表
      templateList: [], // 模板列表
      stickerImageList: [], // AI图片列表
      customStickerImageList: [], // 照片列表
      decorateType: null,
      decorateIndex: 0,
      isEdit: false,
      isFocus: false, //是否选中贴纸
      // 历史记录
      history: [],
      maxHistory: 20,
      historyIndex: 0,
      originalState: null, // 初始状态快照
    };
  },
  computed: {
    ...mapGetters(["phoneModelId"]),
    canEdit() {
      return this.$refs.phoneModel.activeMaterialIndex != null;
    },
    noneAiImage() {
      return (
        this.stickerImageList.filter((item) => {
          return item.type == this.decorateTabsId;
        }).length == 0
      );
    },
  },
  methods: {
    getAiImage() {
      console.log("sss");
      uni.switchTab({
        url: "/pages/example",
      });
    },
    // 选择手机型号
    selectPhoneModel(data) {
      this.infoData.phoneModelId = data;
      this.getMaterialList();
    },
    // 获取机壳列表
    async getMaterialList(init) {
      const data = await getSkuList({
        materialMap: {
          11: this.infoData.phoneModelId,
        },
        materialSubType: this.infoData.materialSubType,
        pageSize: 50,
      });
      this.materialList = data.data;

      // 优先使用store中的材质
      const storeMaterial = this.$store.getters.getCurrentMaterial;
      if (storeMaterial) {
        const idx = data.data.findIndex((item) => item.id === storeMaterial.id);
        if (idx > -1) {
          return this.selectMaterial(storeMaterial, idx, init);
        }
      }

      if (init) {
        let idx = data.data.findIndex((item) => {
          return this.infoData.skuId == item.id;
        });
        this.selectMaterial(this.materialList[idx], idx, init);
      } else {
        let idx = data.data.findIndex((item) => {
          return this.activeMaterialMap[10] == item.materialMap[10];
        });
        idx = idx == -1 ? 0 : idx;
        this.selectMaterial(this.materialList[idx], idx);
      }
    },
    // 选择机壳材质
    selectMaterial(data, index, init) {
      console.log("设置机壳材质", data, index, init);
      this.$store.commit("setCurrentMaterial", data); // 新增当前选择的机壳材质到vuex
      // this.$refs.phoneModel.activeMaterialIndex = index
      this.$refs.phoneModel.activeMaterialIndex = data.id;
      this.activeMaterialId = data.id;
      this.activeMaterialMap = data.materialMap;
      this.$refs.phoneModel.name = data.name;
      this.$refs.phoneModel.baseImageUrl = this.topMaterialUrl =
        data.frameImageUrl;
      this.$refs.phoneModel.frameImageUrl = this.bottomMaterialUrl =
        data.baseImageUrl;
      this.getDecorateList(init);
      this.$refs.phoneModel.materialListShow = false;
    },
    // 上传照片
    uploadImage() {
      const _this = this;
      uni.chooseMedia({
        count: 1, // 最多可以选择的文件个数
        sourceType: ["album", "camera"], // 从相册选择或是直接调起相机
        mediaType: ["image"], // 可以选定的文件类型
        camera: "back", // 默认后置摄像头，front为前置摄像头
        success: function (res) {
          if (res.tempFiles[0].size > 10 * 1024 * 1024) {
            uni.showToast({
              title: "图片不能大于10M",
              icon: "none",
              duration: 2000,
            });
            return;
          }
          // 上传图片
          uploadStickerImage(res.tempFiles[0].tempFilePath, (response) => {
            let image = JSON.parse(response.data).data;
            const imageData = {
              id: image.id,
              imageUrl: image.imageUrl,
              height: image.height,
              width: image.width,
            };
            // 将图片放入图片列表中
            _this.customStickerImageList.unshift(imageData);
            // 将图片放入贴纸列表中
            _this.selectDecorate(imageData, 30);
          });
        },
        fail: function (err) {
          console.error("选择失败", err);
        },
      });
    },
    // 获取贴纸库
    getDecorateList(init) {
      let [{ ...item }] = this.materialList.filter((d) => {
        return d.id == this.$refs.phoneModel.activeMaterialIndex;
      });
      getDecorateList({
        materialMap: {
          // 10: this.materialList[this.$refs.phoneModel.activeMaterialIndex].materialMap[10],
          // 11: this.infoData.phoneModelId,
          10: item.materialMap[10],
          11: item.materialMap[11],
        },
      }).then((res) => {
        // 贴纸列表0
        this.decorationList = res.data.decorationList;
        // 配饰列表1
        // this.accessoriesList = res.data.accessoriesList
        // ai图像列表2
        this.stickerImageList = res.data.stickerImageList;
        // 模板列表3
        this.templateList = res.data.templateList;
        // 照片列表
        this.customStickerImageList = res.data.customStickerImageList;

        // 贴纸tag列表
        this.decorationTagList = [
          {
            id: 0,
            type: 2,
            name: "全部",
          },
          ...res.data.decorationTagList,
        ];
        // 渲染模板
        if (init) {
          this.renderModel(this.infoData);
        }
      });
    },
    // 选择贴纸列表类型
    selectDecorateType: connect_throttle(async function(type)  { 
      if (this.decorateType == type) {
        this.decorateType = null;
        this.moreDecorate = false;
      } else {
        this.decorateType = type;
        if (type == 0) {
          this.decorateTabsId = this.decorationTagList[0].id;
          this.decorateTabsIndex = 0;
        }
        if (type == 2) {
          this.decorateTabsId = 23;
          this.decorateTabsIndex = 0;
        }
        if (type == 3) {
          this.decorateTabsId = this.templateList[0].subType;
          this.decorateTabsIndex = this.templateTagList.findIndex((item) => {
            return item.id == this.decorateTabsId;
          });
        }
      }
    },500),
    // 切换贴纸标签
    switchDecorateTab(e) {
      this.decorateTabsId = e.id;
      this.decorateTabsIndex = e.index;
    },
    // 选择贴纸
    selectDecorate(item, type) {
      let newItem = JSON.parse(JSON.stringify(item));
      // 贴纸为用户上传照片时(type==30)，若高度大于1000，则按照1000的0.9倍缩放，若宽度大于750，则按照1000的0.7倍缩放
      let scale =
        item.height > 1000 || item.width > 750
          ? item.height > item.width
            ? 900 / item.height
            : 700 / item.width
          : 1;
      newItem = Object.assign(newItem, {
        type,
        x: 500 - newItem.width / 2, //居中
        y: 500 - newItem.height / 2,
        scaleX: type == "30" ? scale : 1,
        scaleY: type == "30" ? scale : 1,
        rotationAngle: 0,
        index: this.decorateIndex + 1,
        sortId: this.decorateIndex,
      });
      this.activeDecorates.push(newItem);
      this.activeDecorates.sort((a, b) => {
        return b.index - a.index;
      });
      this.decorateIndex++;
      // this.decorateType = null
      this.writeHistory(this.activeDecorates);
      this.moreDecorate = false;
    },
    // 复制贴纸
    copyDecorate(data) {
      data.sortId = this.decorateIndex;
      this.activeDecorates.push(data);
      this.activeDecorates.sort((a, b) => {
        return b.index - a.index;
      });
      this.decorateIndex++;
      this.writeHistory(this.activeDecorates);
    },
    // 移除贴纸
    removeDecorate(data) {
      let index = this.activeDecorates.findIndex((item) => {
        return item.sortId == data;
      });
      this.activeDecorates.splice(index, 1);
      this.$refs.diyEdit.setFocus();
      this.writeHistory(this.activeDecorates);
    },
    // 微调贴纸位置
    translateDecorate(x, y) {
      this.$refs.diyEdit.translate(x, y);
      this.translateTimer = setInterval(() => {
        this.$refs.diyEdit.translate(x, y);
      }, 100);
    },
    translateDecorateEnd() {
      clearInterval(this.translateTimer);
      // this.writeHistory(this.activeDecorates)
    },
    // 显示图层调整窗口
    showCoverage() {
      this.$refs.diyEdit.setFocus();
      this.$refs.coverage.isShow = true;
    },
    // 调整贴纸的图层顺序
    changeIndex(data) {
      let index = data.length;
      data.forEach((item) => {
        item.index = index;
        index--;
      });
      this.activeDecorates = data;
      this.writeHistory(this.activeDecorates);
    },
    // 确定保存
    save() {
      uni.showLoading();
      let decorateList = this.$refs.diyEdit.decorateList;
      let canvasData = {
        bottomMaterialUrl: this.bottomMaterialUrl,
        topMaterialUrl: this.topMaterialUrl,
        stickerImageList: decorateList,
        id: this.infoData.id,
        skuId: this.activeMaterialId,
      };
      // console.log(canvasData);
      // 生成效果图
      generateCanvas(canvasData, decorateList.length * 300 + 1000).then(
        (res) => {
          this.img = res;
          // 提交编辑
          submitCustomImage(
            res,
            {
              data: JSON.stringify(canvasData),
            },
            (r) => {
              uni.hideLoading();
              // console.log(JSON.parse(r.data).data);
              if (this.isEdit) {
                uni.navigateBack();
              } else {
                uni.redirectTo({
                  url: `/pages/myCustom/customView?id=${
                    JSON.parse(r.data).data
                  }`,
                });
              }
            }
          );
        }
      );
      this.originalState = JSON.stringify(this.activeDecorates);
      uni.setStorageSync("hasUnsavedChanges", true);
    },
    // 获取详情
    getCustomDetail(id, temp) {
      getCustomDetail({
        // phoneModelId: this.infoData.phoneModelId,
        id,
      }).then((res) => {
        this.infoData = res.data;
        if (temp) {
          this.infoData.id = null;
        }
        this.infoData.phoneModelId = res.data.materialMap[11];
        this.getMaterialList("init");
      });
    },
    // 获取模板详情
    getTemplateInfo(id, subType) {
      getCustomDetail({
        id,
      }).then((res) => {
        if (subType == 1 || subType == 3) {
          let idx = this.activeDecorates.findIndex((item) => {
            return item.background == true;
          });
          if (idx != -1) {
            this.activeDecorates.splice(idx, 1);
          }
          let data = res.data.stickerImageList[0];
          data.index = 0;
          data.sortId = this.decorateIndex;
          this.decorateIndex++;
          this.$nextTick(() => {
            this.activeDecorates.push(data);
            this.writeHistory(this.activeDecorates);
          });
        } else {
          this.renderModel(res.data);
        }
        this.moreDecorate = false;
      });
    },
    // 渲染模板内容
    renderModel(data) {
      // 添加贴纸
      this.activeDecorates = [];
      data.stickerImageList.forEach((item) => {
        let newItem = JSON.parse(JSON.stringify(item));
        // sortId用于区分多个id相同的贴纸
        newItem.sortId = this.decorateIndex;
        this.activeDecorates.push(newItem);
        this.decorateIndex++;
        this.activeDecorates.sort((a, b) => {
          return b.index - a.index;
        });
      });
      this.writeHistory(this.activeDecorates);
      // this.decorateIndex = this.activeDecorates[0].index
      uni.hideLoading();
    },
    // 点击编辑面板
    editViewClick() {
      this.moreDecorate = false;
      this.$refs.phoneModel.materialListShow = false;
    },
    // 删除照片
    deleteImage(id) {
      const _this = this;
      uni.showModal({
        content: "确认要删除",
        success: function (res) {
          if (res.confirm) {
            deleteImage({
              id,
            }).then((res) => {
              const index1 = _this.customStickerImageList.findIndex((item) => {
                return item.id == id;
              });
              if (index1 != -1) {
                _this.customStickerImageList.splice(index1, 1);
              }
              //
              _this.activeDecorates = _this.activeDecorates.filter((item) => {
                return item.id != id;
              });
              _this.writeHistory(_this.activeDecorates);
            });
          }
        },
      });
    },
    // 监听贴纸的形变
    changeDecorate(data) {
      // this.activeDecorates = data
      this.writeHistory(data);
    },
    // 读写历史记录
    writeHistory(data) {
      let _data = JSON.parse(JSON.stringify(data));
      // 如果index小于数组长度，则清除掉index之后的数据
      this.history.splice(this.historyIndex + 1);
      // 如果数组超出最大长度，清除掉第一项
      if (this.history.length >= this.maxHistory) {
        this.history.shift();
      }
      // 写入最后一项,index修改为数组最后一项
      this.history.push(_data);
      this.historyIndex = this.history.length - 1;
      console.log(this.history, this.historyIndex);
    },
    readHistory(index) {
      this.activeDecorates = JSON.parse(
        JSON.stringify(this.history[this.historyIndex])
      );
      this.$refs.diyEdit.decorateList = this.activeDecorates;
      // console.log('readHistory:', this.history, this.historyIndex);
      this.$refs.diyEdit.setFocus();
    },
    // 前进
    forward() {
      if (this.historyIndex < this.history.length - 1) {
        this.historyIndex++;
        this.readHistory();
        // 前进后检查状态差异
        this.checkStateChange();
      }
      // this.historyIndex =
      // 	this.historyIndex >= this.history.length - 1 ?
      // 	this.history.length - 1 : this.historyIndex + 1
      // this.readHistory()
    },
    // 后退
    backward() {
      if (this.historyIndex > 0) {
        this.historyIndex--;
        this.readHistory();
        // 后退后检查状态差异
        this.checkStateChange();
      }
      // this.historyIndex =
      // 	this.historyIndex <= 0 ?
      // 	0 : this.historyIndex - 1
      // this.readHistory()
    },
    // 新增状态对比方法
    checkStateChange() {
      const currentState = JSON.stringify(this.activeDecorates);
      uni.setStorageSync(
        "hasUnsavedChanges",
        currentState !== this.originalState
      );
    },
  },
  onLoad(e) {
    console.log("diyPhoneCase onLoad", e);
    // 新增材质参数解析
    if (e.material) {
      const material = JSON.parse(e.material);
      this.$store.commit("setCurrentMaterial", material);
      this.activeMaterialId = material.id;
    }
    if (e.id) {
      this.getCustomDetail(e.id);
      uni.showLoading();
      this.isEdit = true;
    } else if (e.tempId) {
      this.getCustomDetail(e.tempId, true);
      uni.showLoading();
      this.isEdit = false;
    } else {
      this.infoData.phoneModelId = this.phoneModelId;
      this.getMaterialList();
    }
    this.originalState = JSON.stringify(this.activeDecorates);
  },
};
</script>

<style lang="scss">
	.diyPhoneCase-page {
		display: flex;
		flex-direction: column;
		height: 100%;
		background: #fff;

		.tabs {
			padding: 17rpx;
			background-color: #fff;
		}

		.decorate-content {
			height: 100%;
			overflow: hidden;
			position: relative;

			.tips {
				position: absolute;
				top: 600rpx;
				left: 50%;
				transform: translateX(-50%);
				color: #efefef;
				z-index: 1;
				font-size: 35rpx;
				text-shadow: 0rpx 0rpx 11rpx #333;
			}

			.eidt-view {
				height: 1000rpx;
				background-color: #fff;
			}

			.type-tabbar {
				height: 140rpx;
				width: 100%;
				display: flex;
				position: absolute;
				bottom: 0;
				background: #fff;
				overflow: hidden;
				z-index: 99;

				.type-item {
					flex: 1;
					text-align: center;
					margin: 20rpx 20rpx 0;

					&.active {
						background-color: #e8e8e8;
					}

					image {
						height: 80rpx;
						width: 60rpx;
					}

					text {
						font-size: 23rpx;
					}
				}
			}

			.operation-tabbar {
				position: fixed; // 改为固定定位
				bottom: 250rpx;
				left: 0;
				right: 0;
				// z-index: 9999;     // 确保最高层级
				height: 100rpx;
				background: #fff;
				box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.1);
				// position: relative;

				.left-control {
					height: 70rpx;
					display: flex;
					margin-left: 23rpx;

					.translate {
						position: absolute;
						left: 50%;
						transform: translateX(-50%);
					}

					.control-btn {
						width: 70rpx;
						height: 60rpx;

						&.next {
							transform: scaleX(-1);
						}


						&.left {
							transform: rotate(0deg);
						}

						&.up {
							transform: rotate(90deg);
						}

						&.down {
							transform: rotate(270deg);
						}

						&.right {
							transform: rotate(180deg);
						}

						&.disable {
							opacity: 0.5;
						}
					}
				}

				.coverage {
					position: absolute;
					top: 0rpx;
					right: 17rpx;
					height: 70rpx;
					width: 70rpx;
					background: #fff;
					box-shadow: 0rpx 1rpx 11rpx 0rpx #666;
					border-radius: 50%;
					padding: 15rpx;

					image {
						height: 100%;
						width: 100%;
					}
				}
			}

			.decorate-list {
				height: calc(100% - 880rpx);
				width: 100%;
				position: absolute;
				border-top: 1rpx solid #e2e2e2;
				transition: 0.3s;
				bottom: 140rpx;
				background-color: #F6F6F6;
				z-index: 98;
				display: flex;
				flex-direction: column;

				&.more {
					height: calc(100% - 200rpx);
				}

				&.hide {
					bottom: -320rpx;
					height: calc(100% - 950rpx);
				}

				.tips1 {
					position: absolute;
					top: 18rpx;
					left: 30rpx;
					color: #969696;
				}

				.more {
					height: 60rpx;
					width: 118rpx;
					background-color: #F6F6F6;
					position: absolute;
					top: -60rpx;
					left: 17rpx;
					border-radius: 17rpx 17rpx 0rpx 0;
					border: 1rpx solid #e2e2e2;
					border-bottom: none;
					text-align: center;
					line-height: 60rpx;
					color: #999;
				}

				.decorate-scroll {
					height: calc(100% - 77rpx);
					// overflow: hidden;
					width: 100%;
					padding: 17rpx 0;
					flex-grow: 1;

					.list {
						&.ai-list{
							grid-template-columns: repeat(3, 1fr);
							.decorate-item {
								// height: 115rpx;
								height: 90rpx;
								.image{
									height: 50rpx;
								}
							}

						}
						grid-template-columns: repeat(4, 1fr);
						grid-gap: 17rpx;
						display: grid;
						margin: 0 34rpx 17rpx;

						.decorate-item {
							background-color: #fff;
							height: 165rpx;
							position: relative;

							&.upload {
								padding: 34rpx;
								text-align: center;

								image {
									height: 50rpx;
									width: 50rpx;
									margin: 17rpx;
									box-sizing: border-box;
								}

								.text {
									white-space: nowrap;
								}
							}

							// image {
							// 	height: calc(100% - 35rpx);
							// 	width: calc(100% - 35rpx);
							// 	margin: 17rpx;
							// }

							// image {
							// 	height: calc(100% - 10rpx);
							// 	width: calc(100% - 10rpx);
							// 	margin: 5rpx;
							// }

							image {
								height: calc(120% - 25rpx);
								width: calc(100%);
								margin: 5rpx;
							}

							&.temp-item {
								height: 214rpx;
								overflow: hidden;

								image {
									height: 100%;
									width: 100%;
									margin: auto;
									transform: scale(1.3);
								}
							}

							&.active {
								opacity: 0.7;

								.radio {
									position: absolute;
									right: 17rpx;
									top: 17rpx;
								}
							}

							.delete {
								height: 43rpx;
								width: 43rpx;
								background: #333333;
								color: #fff;
								font-size: 43rpx;
								position: absolute;
								top: 17rpx;
								right: 17rpx;
								text-align: center;
								line-height: 43rpx;
								border-radius: 50%;
								opacity: 0.8;
							}
						}
					}

					.get-ai-image{
						height: 100%;
						display: flex;
						align-items: center;
						justify-content: center;
						.get-ai-image-text{
							width: 200rpx;
							height: 50rpx;
							line-height: 50rpx;
							text-align: center;
							border: 1px solid #999;
							border-radius: 50rpx;
						}
					}
				}
			}
		}

		.btn {
			margin: 26rpx 35rpx;

			.btn-next {
				width: 100%;
				height: 78.8rpx;
				border-radius: 78rpx;
				font-size: 35rpx;
				box-sizing: border-box;
				text-align: center;
				line-height: 78.8rpx;
				background-color: #333;
				color: #fff;

				&.disable {
					opacity: 0.7;
				}
			}
		}

		.coverage-view {
			width: 30vw;
			margin-top: 190rpx;

			.coverage-item {
				margin: 17rpx 10rpx;

				.delete {
					height: 35rpx;
					width: 35rpx;
					position: relative;
					top: -29rpx;
					margin-right: 17rpx;
				}

				.image {
					height: 100rpx;
					width: 100rpx;
					border: 2rpx solid;
				}

				.move {
					height: 35rpx;
					width: 35rpx;
					position: relative;
					top: -29rpx;
					margin-left: 17rpx;
				}
			}

		}
	}
</style>
